<template>
  <div v-if="isOpen" class="fixed inset-0 z-50 flex items-center justify-center">
    <div class="absolute inset-0 bg-black opacity-50" @click="close"></div>
    <div class="bg-white dark:bg-gray-800 rounded-lg shadow-xl z-10 p-6 w-full max-w-md">
      <h2 class="text-xl font-bold mb-4 dark:text-white">加入群组</h2>
      
      <div class="mb-4">
        <label for="group-code" class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
          请输入群组邀请码
        </label>
        <input
          id="group-code"
          v-model="groupCode"
          type="text"
          placeholder="输入6位群组邀请码"
          maxlength="6"
          class="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm placeholder-gray-400 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 dark:bg-gray-700 dark:border-gray-600 dark:text-white dark:placeholder-gray-500"
          :disabled="isLoading || isJoining"
          @input="formatGroupCode"
          @keyup.enter="searchGroup"
        />
        <p class="mt-1 text-sm text-gray-500 dark:text-gray-400">
          邀请码通常是6位数字和字母的组合
        </p>
      </div>

      <!-- 搜索结果 -->
      <div v-if="searchedGroup" class="mb-4 p-4 bg-gray-50 dark:bg-gray-700 rounded-md">
        <div class="flex items-center space-x-3 mb-3">
          <div class="text-2xl">{{ searchedGroup.group_avatar || '👥' }}</div>
          <div>
            <h3 class="font-medium dark:text-white">{{ searchedGroup.name }}</h3>
            <p v-if="searchedGroup.description" class="text-sm text-gray-600 dark:text-gray-300">
              {{ searchedGroup.description }}
            </p>
          </div>
        </div>
        <button
          @click="joinGroup"
          :disabled="isJoining"
          class="w-full px-4 py-2 text-sm font-medium text-white bg-indigo-600 border border-transparent rounded-md shadow-sm hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 disabled:opacity-50"
        >
          {{ isJoining ? '申请中...' : '申请加入' }}
        </button>
      </div>

      <!-- 加载状态 -->
      <div v-if="isLoading" class="mb-4 text-center py-4">
        <div class="animate-spin rounded-full h-8 w-8 border-t-2 border-b-2 border-indigo-500 mx-auto"></div>
        <p class="mt-2 text-sm text-gray-500 dark:text-gray-400">搜索群组中...</p>
      </div>

      <!-- 错误提示 -->
      <div v-if="error" class="mb-4">
        <div v-if="errorType === 'not-found'" 
             class="p-3 bg-yellow-50 dark:bg-yellow-900/20 border border-yellow-200 dark:border-yellow-800 rounded-md">
          <div class="flex items-start space-x-2">
            <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5 text-yellow-500 mt-0.5 flex-shrink-0" viewBox="0 0 20 20" fill="currentColor">
              <path fill-rule="evenodd" d="M8.257 3.099c.765-1.36 2.722-1.36 3.486 0l5.58 9.92c.75 1.334-.213 2.98-1.742 2.98H4.42c-1.53 0-2.493-1.646-1.743-2.98l5.58-9.92zM11 13a1 1 0 11-2 0 1 1 0 012 0zm-1-8a1 1 0 00-1 1v3a1 1 0 002 0V6a1 1 0 00-1-1z" clip-rule="evenodd" />
            </svg>
            <div class="text-sm text-yellow-700 dark:text-yellow-300">
              <p class="font-medium">群组未找到</p>
              <p class="mt-1">请检查邀请码是否正确，或向群主确认邀请码是否有效</p>
            </div>
          </div>
        </div>
        
        <div v-else-if="errorType === 'already-member'"
             class="p-3 bg-blue-50 dark:bg-blue-900/20 border border-blue-200 dark:border-blue-800 rounded-md">
          <div class="flex items-start space-x-2">
            <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5 text-blue-500 mt-0.5 flex-shrink-0" viewBox="0 0 20 20" fill="currentColor">
              <path fill-rule="evenodd" d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7-4a1 1 0 11-2 0 1 1 0 012 0zM9 9a1 1 0 000 2v3a1 1 0 001 1h1a1 1 0 100-2v-3a1 1 0 00-1-1H9z" clip-rule="evenodd" />
            </svg>
            <div class="text-sm text-blue-700 dark:text-blue-300">
              <p class="font-medium">您已经是群成员</p>
              <p class="mt-1">{{ error }}</p>
            </div>
          </div>
        </div>

        <div v-else-if="errorType === 'pending'"
             class="p-3 bg-amber-50 dark:bg-amber-900/20 border border-amber-200 dark:border-amber-800 rounded-md">
          <div class="flex items-start space-x-2">
            <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5 text-amber-500 mt-0.5 flex-shrink-0" viewBox="0 0 20 20" fill="currentColor">
              <path d="M10 12a2 2 0 100-4 2 2 0 000 4z" />
              <path fill-rule="evenodd" d="M.458 10C1.732 5.943 5.522 3 10 3s8.268 2.943 9.542 7c-1.274 4.057-5.064 7-9.542 7S1.732 14.057.458 10zM14 10a4 4 0 11-8 0 4 4 0 018 0z" clip-rule="evenodd" />
            </svg>
            <div class="text-sm text-amber-700 dark:text-amber-300">
              <p class="font-medium">申请处理中</p>
              <p class="mt-1">{{ error }}</p>
            </div>
          </div>
        </div>
        
        <div v-else class="p-3 bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-md">
          <div class="flex items-start space-x-2">
            <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5 text-red-500 mt-0.5 flex-shrink-0" viewBox="0 0 20 20" fill="currentColor">
              <path fill-rule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zM8.707 7.293a1 1 0 00-1.414 1.414L8.586 10l-1.293 1.293a1 1 0 101.414 1.414L10 11.414l1.293 1.293a1 1 0 001.414-1.414L11.414 10l1.293-1.293a1 1 0 00-1.414-1.414L10 8.586 8.707 7.293z" clip-rule="evenodd" />
            </svg>
            <div class="text-sm text-red-700 dark:text-red-300">
              <p class="font-medium">操作失败</p>
              <p class="mt-1">{{ error }}</p>
            </div>
          </div>
        </div>
      </div>

      <div class="flex justify-end space-x-3 mt-6">
        <button 
          type="button" 
          class="px-4 py-2 text-sm font-medium text-gray-700 bg-white border border-gray-300 rounded-md shadow-sm hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 dark:bg-gray-700 dark:text-gray-300 dark:border-gray-600 dark:hover:bg-gray-600"
          @click="close"
        >
          关闭
        </button>
        <button 
          v-if="!searchedGroup && groupCode.length >= 3"
          type="button" 
          class="px-4 py-2 text-sm font-medium text-white bg-indigo-600 border border-transparent rounded-md shadow-sm hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500"
          :disabled="isLoading"
          @click="searchGroup"
        >
          {{ isLoading ? '搜索中...' : '搜索群组' }}
        </button>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, computed } from 'vue';
import { useToast } from 'vue-toastification';
import axios from 'axios';

export default {
  name: 'JoinGroupModal',
  props: {
    isOpen: {
      type: Boolean,
      required: true
    }
  },
  emits: ['close', 'joined'],
  setup(props, { emit }) {
    const toast = useToast();
    const groupCode = ref('');
    const searchedGroup = ref(null);
    const isLoading = ref(false);
    const isJoining = ref(false);
    const error = ref('');
    const errorType = ref('');

    // 格式化邀请码（转为大写，限制字符）
    const formatGroupCode = () => {
      groupCode.value = groupCode.value.replace(/[^A-Z0-9]/gi, '').toUpperCase();
      // 清除搜索结果和错误
      if (searchedGroup.value) {
        searchedGroup.value = null;
      }
      if (error.value) {
        error.value = '';
        errorType.value = '';
      }
    };

    // 搜索群组
    const searchGroup = async () => {
      if (!groupCode.value || groupCode.value.length < 3) {
        error.value = '请输入至少3位邀请码';
        errorType.value = 'invalid';
        return;
      }

      try {
        isLoading.value = true;
        error.value = '';
        errorType.value = '';
        searchedGroup.value = null;

        const response = await axios.get(`/api/groups/code/${groupCode.value}`);
        searchedGroup.value = response.data;
        
        toast.success('找到群组！');
      } catch (err) {
        console.error('搜索群组失败:', err);
        const errorMessage = err.response?.data?.message || '搜索群组失败';
        
        if (err.response?.status === 404) {
          error.value = '找不到对应的群组，请检查邀请码是否正确';
          errorType.value = 'not-found';
        } else {
          error.value = errorMessage;
          errorType.value = 'failed';
        }
      } finally {
        isLoading.value = false;
      }
    };

    // 申请加入群组
    const joinGroup = async () => {
      if (!searchedGroup.value) return;

      try {
        isJoining.value = true;
        error.value = '';
        errorType.value = '';

        await axios.post(`/api/groups/${searchedGroup.value.id}/join`);
        
        toast.success('加入申请已发送，等待管理员审核');
        emit('joined', searchedGroup.value);
        close();
      } catch (err) {
        console.error('申请加入群组失败:', err);
        const errorMessage = err.response?.data?.message || '申请加入群组失败';
        
        if (errorMessage.includes('已经是该群组的成员')) {
          error.value = errorMessage;
          errorType.value = 'already-member';
        } else if (errorMessage.includes('已经发送过加入请求')) {
          error.value = errorMessage;
          errorType.value = 'pending';
        } else {
          error.value = errorMessage;
          errorType.value = 'failed';
          toast.error(errorMessage);
        }
      } finally {
        isJoining.value = false;
      }
    };

    // 关闭模态框
    const close = () => {
      groupCode.value = '';
      searchedGroup.value = null;
      error.value = '';
      errorType.value = '';
      emit('close');
    };

    return {
      groupCode,
      searchedGroup,
      isLoading,
      isJoining,
      error,
      errorType,
      formatGroupCode,
      searchGroup,
      joinGroup,
      close
    };
  }
};
</script> 